package cn.liujianbo.example.validate.listener;

import org.springframework.boot.context.event.*;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author 刘建波
 * @date 2021-09-07 21:15
 *
 * 注册Listener:
 *      1.启动类修改启动代码
 *          new SpringApplicationBuilder().sources(ValidateApplication.class)
 *                 .listeners(new TestApplicationEventListener()).run(args);
 *      2.增加配置文件
 *
 * 如果使用@Component注解注册的Listener只能监听到ApplicationStarted/ApplicationReady
 *
 * 自定义事件   可以用 ApplicationEventPublisher.publishEvent() 发布事件
 *      1.
 */
public class TestApplicationEventListener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        // springboot应用启动且未作任何处理（除listener注册和初始化）的时候发送ApplicationStartingEvent
        if (applicationEvent instanceof ApplicationStartingEvent) {
            System.out.println("ApplicationStarting");
            return;
        }
        // 确定springboot应用使用的Environment且context创建之前发送这个事件
        if (applicationEvent instanceof ApplicationEnvironmentPreparedEvent) {
            System.out.println("ApplicationEnvironmentPrepared");
            return;
        }
        // context已经创建且没有refresh发送个事件
        if (applicationEvent instanceof ApplicationPreparedEvent) {
            System.out.println("ApplicationPrepared");
            return;
        }
        // context已经refresh且application and command-line runners（如果有） 调用之前发送这个事件
        if (applicationEvent instanceof ApplicationStartedEvent) {
            System.out.println("ApplicationStarted");
            return;
        }
        // application and command-line runners （如果有）执行完后发送这个事件，此时应用已经启动完毕.这个事件比较常用，常常在系统启动完后做一些初始化操作
        if (applicationEvent instanceof ApplicationReadyEvent) {
            System.out.println("ApplicationReady");
            // 取出容器中的bean，执行相应初始化操作
            ConfigurableApplicationContext context = ((ApplicationReadyEvent) applicationEvent).getApplicationContext();
            TestListenerService bean = context.getBean(TestListenerService.class);
            bean.systemInit();
            return;
        }
        // 应用启动失败后产生这个事件
        if (applicationEvent instanceof ApplicationFailedEvent) {
            System.out.println("ApplicationFailed");
            return;
        }
    }
}
